import request from './request'

const STORAGE_PREFIX = '/storage'
const CDN_PREFIX = '/cdn'

/**
 * 存储管理相关接口
 */

// 获取存储统计信息
export function getStorageStatistics() {
  return request({
    url: `${STORAGE_PREFIX}/statistics`,
    method: 'get'
  })
}

// 获取存储分布数据
export function getStorageDistribution() {
  return request({
    url: `${STORAGE_PREFIX}/distribution`,
    method: 'get'
  })
}

// 开始存储分析
export function startStorageAnalysis(options?: {
  includeDeepScan?: boolean
  scanDuplicates?: boolean
  scanCompression?: boolean
}) {
  return request({
    url: `${STORAGE_PREFIX}/analyze`,
    method: 'post',
    data: options
  })
}

// 获取分析结果
export function getAnalysisResult(taskId: string) {
  return request({
    url: `${STORAGE_PREFIX}/analyze/${taskId}`,
    method: 'get'
  })
}

/**
 * 重复文件检测
 */

// 获取重复文件列表
export function getDuplicateFiles(options?: {
  fileType?: string
  minSize?: number
  similarity?: number
}) {
  return request({
    url: `${STORAGE_PREFIX}/duplicates`,
    method: 'get',
    params: options
  })
}

// 获取重复文件组详情
export function getDuplicateGroup(groupId: string) {
  return request({
    url: `${STORAGE_PREFIX}/duplicates/${groupId}`,
    method: 'get'
  })
}

// 清理重复文件
export function cleanDuplicateFiles(groupId: string, keepFileId: string) {
  return request({
    url: `${STORAGE_PREFIX}/duplicates/${groupId}/clean`,
    method: 'post',
    data: { keepFileId }
  })
}

// 批量清理重复文件
export function batchCleanDuplicates(cleanTasks: Array<{
  groupId: string
  keepFileId: string
}>) {
  return request({
    url: `${STORAGE_PREFIX}/duplicates/batch-clean`,
    method: 'post',
    data: cleanTasks
  })
}

/**
 * 压缩优化
 */

// 获取压缩建议
export function getCompressionSuggestions(options?: {
  fileType?: string
  minSize?: number
  maxAge?: number
}) {
  return request({
    url: `${STORAGE_PREFIX}/compression/suggestions`,
    method: 'get',
    params: options
  })
}

// 应用压缩建议
export function applyCompressionSuggestion(suggestionId: string, options?: {
  quality?: number
  format?: string
  preserveOriginal?: boolean
}) {
  return request({
    url: `${STORAGE_PREFIX}/compression/apply/${suggestionId}`,
    method: 'post',
    data: options
  })
}

// 批量压缩文件
export function batchCompressFiles(fileIds: number[], options?: {
  imageQuality?: number
  videoQuality?: string
  generateWebP?: boolean
  preserveOriginal?: boolean
}) {
  return request({
    url: `${STORAGE_PREFIX}/compression/batch`,
    method: 'post',
    data: {
      fileIds,
      options
    }
  })
}

/**
 * 存储清理
 */

// 清理临时文件
export function cleanTemporaryFiles() {
  return request({
    url: `${STORAGE_PREFIX}/cleanup/temp`,
    method: 'post'
  })
}

// 清理缩略图缓存
export function cleanThumbnailCache() {
  return request({
    url: `${STORAGE_PREFIX}/cleanup/thumbnails`,
    method: 'post'
  })
}

// 归档旧文件
export function archiveOldFiles(options: {
  olderThan: number // 天数
  targetLocation: string
  deleteOriginal: boolean
}) {
  return request({
    url: `${STORAGE_PREFIX}/archive`,
    method: 'post',
    data: options
  })
}

/**
 * 批量优化
 */

// 开始批量优化
export function startBatchOptimization(config: {
  compressImages?: boolean
  compressVideos?: boolean
  generateWebP?: boolean
  removeDuplicates?: boolean
  cleanThumbnails?: boolean
  archiveOldFiles?: boolean
  imageQuality?: number
  videoQuality?: string
  archiveAge?: number
}) {
  return request({
    url: `${STORAGE_PREFIX}/optimize/batch`,
    method: 'post',
    data: config
  })
}

// 获取批量优化进度
export function getBatchOptimizationProgress(taskId: string) {
  return request({
    url: `${STORAGE_PREFIX}/optimize/progress/${taskId}`,
    method: 'get'
  })
}

// 取消批量优化
export function cancelBatchOptimization(taskId: string) {
  return request({
    url: `${STORAGE_PREFIX}/optimize/cancel/${taskId}`,
    method: 'post'
  })
}

/**
 * CDN管理相关接口
 */

// 获取CDN统计信息
export function getCDNStatistics() {
  return request({
    url: `${CDN_PREFIX}/statistics`,
    method: 'get'
  })
}

// 获取CDN节点状态
export function getCDNNodes() {
  return request({
    url: `${CDN_PREFIX}/nodes`,
    method: 'get'
  })
}

// 启用/禁用CDN
export function toggleCDN(enabled: boolean) {
  return request({
    url: `${CDN_PREFIX}/toggle`,
    method: 'post',
    data: { enabled }
  })
}

/**
 * CDN缓存管理
 */

// 获取缓存统计
export function getCacheStatistics() {
  return request({
    url: `${CDN_PREFIX}/cache/statistics`,
    method: 'get'
  })
}

// 刷新CDN缓存
export function refreshCDNCache(urls?: string[]) {
  return request({
    url: `${CDN_PREFIX}/cache/refresh`,
    method: 'post',
    data: { urls }
  })
}

// 清空CDN缓存
export function clearCDNCache() {
  return request({
    url: `${CDN_PREFIX}/cache/clear`,
    method: 'post'
  })
}

// 预加载热门文件
export function preloadPopularFiles(options?: {
  limit?: number
  fileTypes?: string[]
  minAccessCount?: number
}) {
  return request({
    url: `${CDN_PREFIX}/cache/preload`,
    method: 'post',
    data: options
  })
}

/**
 * 访问分析
 */

// 获取访问分析数据
export function getAccessAnalytics(timeRange: string = '7d') {
  return request({
    url: `${CDN_PREFIX}/analytics`,
    method: 'get',
    params: { timeRange }
  })
}

// 获取热门文件统计
export function getPopularFiles(options?: {
  limit?: number
  timeRange?: string
  fileType?: string
}) {
  return request({
    url: `${CDN_PREFIX}/analytics/popular-files`,
    method: 'get',
    params: options
  })
}

// 获取带宽使用统计
export function getBandwidthStatistics(timeRange: string = '7d') {
  return request({
    url: `${CDN_PREFIX}/analytics/bandwidth`,
    method: 'get',
    params: { timeRange }
  })
}

// 获取地域访问分析
export function getGeoAccessAnalytics(timeRange: string = '7d') {
  return request({
    url: `${CDN_PREFIX}/analytics/geo`,
    method: 'get',
    params: { timeRange }
  })
}

/**
 * 存储配置管理
 */

// 获取存储配置
export function getStorageConfig() {
  return request({
    url: `${STORAGE_PREFIX}/config`,
    method: 'get'
  })
}

// 更新存储配置
export function updateStorageConfig(config: {
  maxFileSize?: number
  allowedTypes?: string[]
  compressionEnabled?: boolean
  cdnEnabled?: boolean
  autoCleanup?: boolean
  cleanupAge?: number
}) {
  return request({
    url: `${STORAGE_PREFIX}/config`,
    method: 'put',
    data: config
  })
}

// 获取存储提供商配置
export function getStorageProviders() {
  return request({
    url: `${STORAGE_PREFIX}/providers`,
    method: 'get'
  })
}

// 切换存储提供商
export function switchStorageProvider(providerId: string, config: any) {
  return request({
    url: `${STORAGE_PREFIX}/providers/switch`,
    method: 'post',
    data: { providerId, config }
  })
}

/**
 * 数据迁移
 */

// 开始数据迁移
export function startDataMigration(options: {
  sourceProvider: string
  targetProvider: string
  fileTypes?: string[]
  batchSize?: number
}) {
  return request({
    url: `${STORAGE_PREFIX}/migration/start`,
    method: 'post',
    data: options
  })
}

// 获取迁移进度
export function getMigrationProgress(taskId: string) {
  return request({
    url: `${STORAGE_PREFIX}/migration/progress/${taskId}`,
    method: 'get'
  })
}

// 取消数据迁移
export function cancelDataMigration(taskId: string) {
  return request({
    url: `${STORAGE_PREFIX}/migration/cancel/${taskId}`,
    method: 'post'
  })
}

/**
 * 存储健康检查
 */

// 执行存储健康检查
export function performStorageHealthCheck() {
  return request({
    url: `${STORAGE_PREFIX}/health-check`,
    method: 'post'
  })
}

// 获取健康检查报告
export function getHealthCheckReport(reportId: string) {
  return request({
    url: `${STORAGE_PREFIX}/health-check/${reportId}`,
    method: 'get'
  })
}

// 修复存储问题
export function repairStorageIssues(issues: string[]) {
  return request({
    url: `${STORAGE_PREFIX}/repair`,
    method: 'post',
    data: { issues }
  })
}

/**
 * 存储监控和告警
 */

// 获取存储监控数据
export function getStorageMonitoring(timeRange: string = '24h') {
  return request({
    url: `${STORAGE_PREFIX}/monitoring`,
    method: 'get',
    params: { timeRange }
  })
}

// 设置存储告警规则
export function setStorageAlerts(alerts: Array<{
  type: string
  threshold: number
  enabled: boolean
}>) {
  return request({
    url: `${STORAGE_PREFIX}/alerts`,
    method: 'post',
    data: alerts
  })
}

// 获取存储告警记录
export function getStorageAlerts() {
  return request({
    url: `${STORAGE_PREFIX}/alerts`,
    method: 'get'
  })
}

/**
 * TypeScript 类型定义
 */

export interface StorageStatistics {
  totalUsed: number
  totalAvailable: number
  totalCapacity: number
  usagePercentage: number
  fileCount: number
  averageFileSize: number
}

export interface StorageDistribution {
  type: string
  label: string
  size: number
  percentage: number
  fileCount: number
  color: string
}

export interface DuplicateFile {
  id: string
  name: string
  size: number
  type: string
  files: Array<{
    id: string
    path: string
    lastModified: Date
    checksum: string
  }>
  potentialSavings: number
}

export interface CompressionSuggestion {
  id: string
  title: string
  description: string
  priority: 'high' | 'medium' | 'low'
  fileCount: number
  currentSize: number
  estimatedSize: number
  potentialSavings: number
  estimatedTime: number
}

export interface CDNNode {
  id: string
  region: string
  country: string
  city: string
  status: 'healthy' | 'warning' | 'error'
  latency: number
  uptime: number
  lastCheck: Date
}

export interface AccessAnalytics {
  totalRequests: number
  totalTraffic: number
  avgResponseTime: number
  hitRate: number
  topFiles: Array<{
    id: string
    name: string
    requests: number
    traffic: number
  }>
  requestsByHour: Array<{
    hour: string
    requests: number
    traffic: number
  }>
}

export interface OptimizationTask {
  id: string
  type: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  progress: number
  currentFile: string
  processedFiles: number
  totalFiles: number
  savedSpace: number
  estimatedTime: number
  startTime: Date
  endTime?: Date
  error?: string
}